#!/bin/bash

if test -z "$1"
then
	echo "ERROR: You must specify the file to install"
	echo "usage: install.sh file"
	echo "	file	initrd.gz or URL to the ISO version"
	echo
	exit 1
else
	INITRD="$1"
fi

if [ `whoami` != "root" ]
then
	echo "You must be root"
	exit 2
fi

if test -e root
then
	echo "Error: root exists!"
	exit 1
fi


if test -f "$INITRD"
then
	echo "Using $INITRD"
else
	if wget $1 -O opendomo-distro.iso
	then
		mkdir mountpoint_iso
		sudo mount opendomo-distro.iso mountpoint_iso -o loop && cp -vR mountpoint_iso/* . && sudo umount mountpoint_iso
		INITRD="initrd.gz"
	else
		echo "Error: missing $INITRD"
		exit 3
	fi
fi


rm -f img img.gz
cp $INITRD img.gz
gunzip img.gz

umount -l /mnt 2> /dev/null > /dev/null
mount img /mnt -o loop

mkdir root
cp -fRpd /mnt/* root/
install -d root/media/opendomodistro/
install -d root/mnt/odconf/pkgcache
cp -frp pkgcache/* root/mnt/odconf/pkgcache


# start script
echo "
cd /mnt/odconf/pkgcache
for file in \`ls\`; do
	/sbin/pkg_add \$file
done

echo '`cat /etc/resolv.conf`' > /etc/resolv.conf

/etc/init.d/syslog start
/etc/init.d/oddiscovery start
/etc/init.d/inetd start


rm -f /usr/local/opendomo/reboot.sh
rm -f /etc/opendomo/root/config/system/reboot.sh
rm -f /etc/opendomo/root/config/system/reboot.sh.name

rm -f /usr/local/opendomo/saveSystemConfiguration.sh
rm -f /etc/opendomo/root/config/system/saveSystemConfiguration.sh
rm -f /etc/opendomo/root/config/system/saveSystemConfiguration.sh.name

/usr/local/opendomo/updateLanguageFiles.sh

cd /

/bin/sh
" > root/bin/start


# stop script
echo "
/etc/init.d/syslog stop
/etc/init.d/oddiscovery stop
/etc/init.d/inetd stop
" > root/bin/stop



chmod +x root/bin/start
chmod +x root/bin/stop


umount -l /mnt
rm -f img img.gz
